package ic.symbols;

import common.exceptions.SemanticError;
import ic.ast.Visitor;
import ic.ast.decl.DeclClass;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Matan
 * Date: 12/10/13
 * Time: 11:32 AM
 */
public class GlobalSymbolTable extends SymbolTable {

    private Map<String, ClassSymbol> table = new LinkedHashMap<String, ClassSymbol>();

    public List<ClassSymbol> getClassSymbols() {
        List<ClassSymbol> classSymbols = new ArrayList<ClassSymbol>(table.values());
        return classSymbols;
    }

    public GlobalSymbolTable(SymbolTable parent) {
        super(parent);
    }

    @Override
    public Symbol lookup(String name) {
        return getClassSymbol(name);
    }

    @Override
    public SymbolTable lookupTable(String name) {
        if (getClassSymbol(name) != null) {
            return this;
        } else {
            return null;
        }
    }

    @Override
    public Symbol staticLookup(String name) {
        return lookup(name);
    }

    @Override
    public Object accept(Visitor visitor) throws Exception {
        return visitor.visit(this);
    }

    @Override
    public String getCurrentMethodName() {
        return "";
    }

    public void insert(DeclClass newClass) throws SemanticError {
        if (table.containsKey(newClass.getName())) {
            throw new SemanticError("Id " + newClass.getName() + " already defined in current scope");
        }
        table.put(newClass.getName(), new ClassSymbol(newClass));

    }

    public ClassSymbol getClassSymbol(String className) {
        return table.get(className);
    }
}


